package com.ricky.web.api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ricky.base.bean.ApiResult;
import com.ricky.base.bean.DbClient;
import com.ricky.base.bean.SshClient;
import com.ricky.base.util.PathUtil;
import com.ricky.web.table.Service;
import com.ricky.web.util.SshUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.MessageFormat;
import java.util.List;

/**
 * @author Ricky
 * @date 2020/11/19
 */
@Api(tags = "服务管理接口")
@RestController
@RequestMapping("/manager")
public class GuradController {

    @ApiOperation(value = "根据服务id判断服务是否启动")
    @ApiOperationSupport(includeParameters = {"dto.id"})
    @PostMapping("/isServerStartedByid")
    public ApiResult<Boolean> isServerStartedByid(@RequestBody Service dto) throws Exception {
        Service service = getServiceByServerId(dto.getId());
        List<String> pid = SshUtil.getPidListByService(service);

        return ApiResult.success(pid.size() > 0);
    }


    @ApiOperation(value = "根据服务id停止服务")
    @ApiOperationSupport(includeParameters = {"dto.id"})
    @PostMapping("/stopServerById")
    public ApiResult<Boolean> stopServerById(@RequestBody Service dto) throws Exception {
        Service service = getServiceByServerId(dto.getId());
        List<String> pid = SshUtil.getPidListByService(service);

        if (pid.size() <= 0) {
            throw new RuntimeException("服务未启动");
        }

        try (SshClient sshClient = SshUtil.getSshClientByServer(service.getServer())) {
            for (String s : pid) {
                sshClient.exec(MessageFormat.format("kill -9 {0}", s));
            }
        }

        return ApiResult.success(true);
    }

    @ApiOperation(value = "根据服务id启动服务")
    @ApiOperationSupport(includeParameters = {"dto.id"})
    @PostMapping("/startServerById")
    public ApiResult<Boolean> startServerById(@RequestBody Service dto) throws Exception {
        Service service = getServiceByServerId(dto.getId());
        String path = service.getPath();

        try (SshClient sshClient = SshUtil.getSshClientByServer(service.getServer())) {
            String startCommand = service.getStartCommand();
            sshClient.exec("cd " + path + " && " + startCommand);
        }

        return ApiResult.success(true);
    }

    @ApiOperation(value = "根据服务id重启服务")
    @ApiOperationSupport(includeParameters = {"dto.id"})
    @PostMapping("/restartServerById")
    public ApiResult<Boolean> restartServerById(@RequestBody Service dto) throws Exception {
        Service service = getServiceByServerId(dto.getId());
        List<String> pid = SshUtil.getPidListByService(service);

        if (pid.size() <= 0) {
            throw new RuntimeException("服务未启动");
        }


        try (SshClient sshClient = SshUtil.getSshClientByServer(service.getServer())) {
            for (String s : pid) {
                sshClient.exec(MessageFormat.format("kill -9 {0}", s));
            }
            String path = service.getPath();
            String startCommand = service.getStartCommand();

            sshClient.exec("cd " + path + " && " + startCommand);
        }

        return ApiResult.success(true);
    }

    @ApiOperation(value = "根据服务id升级服务")
    @ApiOperationSupport(includeParameters = {"id", "jarFile"})
    @PostMapping("/updateServerById")
    public ApiResult<Boolean> updateServerById(Service dto, MultipartFile jarFile) throws Exception {
        Service service = getServiceByServerId(dto.getId());
        List<String> pid = SshUtil.getPidListByService(service);

        try (SshClient sshClient = SshUtil.getSshClientByServer(service.getServer())) {
            for (String s : pid) {
                sshClient.exec(MessageFormat.format("kill -9 {0}", s));
            }
            String path = service.getPath();
            String fileName = service.getFileName();

            sshClient.uploadDile(path, jarFile, fileName);

            if (pid.size() > 0) {
                String startCommand = service.getStartCommand();

                sshClient.exec("cd " + path + " && " + startCommand);
            }
        }

        return ApiResult.success(true);
    }

    private Service getServiceByServerId(String serverId) throws Exception {
        DbClient dbClient = new DbClient("database.db");

        Service service = dbClient.getById(serverId, Service.class);

        dbClient.close();

        if (service == null) {
            throw new RuntimeException("没有该服务，请检查服务id是否正确");
        }

        return service;
    }

    public static void main(String[] args) {
        System.out.println(PathUtil.getFullPath("/home/swx/test"));
        System.out.println(PathUtil.getFullPath("/home/swx/test/"));
    }
}
